package com.dailyblue.java.spring.rocketmq.顺序消息;

import com.dailyblue.java.spring.rocketmq.bean.Student;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class 局部顺序消息的发送 {
    public static void main(String[] args) throws Exception {
        // 创建消息生产者 producer，并指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("zhuoyue01");
        // 指定 NameSrv 地址
        producer.setNamesrvAddr("192.168.160.88:9876");
        // 启动 producer
        producer.start();
        // 分别是班级编号前缀和班级学生序号
        String[] c = {"c1", "c2", "c3", "c4"};
        int[] c2 = {1, 1, 1, 1};
        for (int i = 1; i < 21; i++) {
            String topic = "TopicA";
            String tags = "shunxu";
            int random = (int) (Math.random() * 4); //0 1 2 3
            Student s = new Student();
            s.setId(c[random] + c2[random]);
            s.setName("测试");
            s.setClassId(random + 1);
            c2[random] = c2[random] + 1;
            Message message = new Message(topic, tags, s.toString().getBytes(StandardCharsets.UTF_8));
            producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    return list.get(random);
                }
            }, null);
        }
        producer.shutdown();
    }
}
